import { useRequest } from "ahooks";
import { Typography } from "antd";
import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { getComponentStatService } from "../../../services/question";
import { getComponentConfByType } from "../../components/QuestionComponents";

type PropsType = {
  config: {
    selectedComponentId: string;
    selectedComponentType: string;
  };
};

const ChartStat: React.FC<PropsType> = (props: PropsType) => {
  const {
    config: { selectedComponentId, selectedComponentType },
  } = props;
  const { id = "" } = useParams();
  const [stat, setStat] = useState([]);
  const { run } = useRequest(
    async (questionId, componentId) =>
      await getComponentStatService(questionId, componentId),
    {
      manual: true,
      onSuccess(res) {
        setStat(res.stat);
      },
    }
  );

  useEffect(() => {
    if (!selectedComponentType) return;
    const { StatComponent } = getComponentConfByType(selectedComponentType);
    if (selectedComponentId && StatComponent) {
      setStat([]);
      run(id, selectedComponentId);
    }
  }, [selectedComponentType, selectedComponentId]);

  function genStatElem() {
    if (!selectedComponentId) return <div>未选中组件</div>;
    const { StatComponent } = getComponentConfByType(selectedComponentType);
    if (!StatComponent) return <div>该组件无统计图表</div>;

    return <StatComponent stat={stat} />;
  }

  return (
    <div style={{ height: "100%", textAlign: "center" }}>
      <Typography.Title level={3}>图表统计</Typography.Title>
      <div style={{ height: "364px" }}>{genStatElem()}</div>
    </div>
  );
};

export default ChartStat;
